06. Exercise: Display SleepQuality Data

L7 07 Implementing An Adapter SC

  1. In SleepNightAdapter, onCreateViewHolder(), inflate the text_item_view layout and return the ViewHolder.

    Get the LayoutInflater from parent.context and inflate R.layout.text_item_view.

    Remember to pass false to attachParent since the RecyclerView will take care of attaching it for us.

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TextItemViewHolder {
    val layoutInflater = LayoutInflater.from(parent.context)
    val view = layoutInflater
    .inflate(R.layout.text_item_view, parent, false) as TextView
    return TextItemViewHolder(view)
    }

  2. In SleepNightAdapter, add a custom setter to data that calls notifyDataSetChanged() and tell Kotlin to save the new value by setting field = value.

    set(value) {
      field = value
      notifyDataSetChanged()
    }


  3. In SleepTrackerFragment, create a new SleepNightAdapter, and use binding to associate it with the RecyclerView:

binding.sleepList.adapter = adapter 


  1. Create an observer on sleepTrackerViewModel.nights that sets the Adapter when there is new data.

    LiveData observers are sometimes passed null, so make sure you check for null.

Debugging tips

If your app compiles but doesn't work, here are a few things to check:

  • Make sure you've added at least one night of sleep.
  • Do you call notifyDataSetChanged() in SleepNightAdapter?
  • Try setting a breakpoint to make sure it's getting called.
  • Did you register an observer on sleepTrackerViewModel.nights in SleepTrackerFragment?
  • Did you set the adapter in SleepTrackerFragment with binding.sleepList.adapter = adapter?
  • Does data in SleepNightAdapter hold a non-empty list?
  • Try setting a breakpoint in the setter and getItemCount().

If you want to start at this step, you can download this exercise from: Step.02-Exercise-Display-Data.

You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.

Once you’re done, you can check your solution against the solution we’ve provided here: Step.02-Solution-Display-Data, or using this git diff.

Task Description:

Complete the following steps to create to implement the adapter.

Task List:

Task Feedback:

Congrats! You've finished your RecyclerView adapter! Next we'll we'll take another look at onBindViewHolder to explore it further.

Reference Documentation